package com.meixiaoliang.portal.core.shiro;

import java.util.List;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import com.meixiaoliang.portal.core.util.AssertUtil;
import com.meixiaoliang.portal.modular.system.model.User;
import com.meixiaoliang.portal.modular.system.model.enums.BooleanEnum;
import com.meixiaoliang.portal.modular.system.service.MenuService;
import com.meixiaoliang.portal.modular.system.service.RoleService;
import com.meixiaoliang.portal.modular.system.service.UserService;

/**
 * 用户名+密码登录及授权，同理后续可添加手机号码+密码、邮箱+密码登录
 */
public class UserNameRealm extends AuthorizingRealm {

    private Logger      logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private MenuService menuService;
    /** 密码加密的盐 */
    @Value("${password.salt}")
    public String       salt;
    /** 密码转换次数 */
    @Value("${password.transTime}")
    public int          transTime;

    /**
     * 授权，即用户权限判别
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        // 登录用户 id
        User user = (User) principalCollection.getPrimaryPrincipal();
        Integer userId = user.getId();
        // 获取角色、权限
        List<String> roleList = roleService.listCodeByUserId(userId);
        List<String> permissionList = menuService.listPermissionByUserId(userId);
        // 返回授权信息
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.addRoles(roleList);
        simpleAuthorizationInfo.addStringPermissions(permissionList);
        return simpleAuthorizationInfo;
    }

    /**
     * 认证，即用户登录
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        // 登录用户名
        String userName = (String) authenticationToken.getPrincipal();
        // 用户名找用户
        User user = userService.getByName(userName);
        // user 为 null, 该用户不存在
        if (user == null) {
            return null;
        }
        // 用户密码必须存在即初始化
        AssertUtil.notBlank(user.getPassword(), "用户密码未初始化，请初始化后再登录");
        // 用户禁止登录
        if (BooleanEnum.FALSE.getCode() == user.getStatus()) {
            throw new DisabledAccountException();
        }
        return new SimpleAuthenticationInfo(user, user.getPassword(), getName());
    }

}
